/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeeplus.common.bean.Node;
import com.jeeplus.common.bean.TreeNode;
import com.jeeplus.common.service.TreeService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.TreeNodeUtils;
import com.jeeplus.modules.sys.dao.AreaDao;
import com.jeeplus.modules.sys.entity.Area;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * 区域Service
 * @author jeeplus
 * @version 2014-05-16
 */
@Service
@Transactional(readOnly = true)
public class AreaService extends TreeService<AreaDao, Area> {

	public List<Area> findAll(){
		return UserUtils.getAreaList();
	}

	@Transactional(readOnly = false)
	public void save(Area area) {
		super.save(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}
	
	@Transactional(readOnly = false)
	public void delete(Area area) {
		super.delete(area);
		UserUtils.removeCache(UserUtils.CACHE_AREA_LIST);
	}
	
	/**
	 * 获取区域树状数据
	 * @param extId
	 * @return
	 */
	public List<TreeNode> tree(@RequestParam(required=false) String extId) {
		List<Node> nodes = new ArrayList<Node>();
		List<Area> list = this.findAll();
		String rootId = "86";
		for (int i=0; i<list.size(); i++){
			Area e = list.get(i);
			if(rootId.equals(e.getId())){
				continue;
			}
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Node node = new Node();
				node.setId(e.getId());
				node.setParentId(e.getParentId());
				node.setLabel(e.getName());
				nodes.add(node);
			}
		}
		return TreeNodeUtils.generateTree(nodes, rootId);
	}
	
}
